package net.stuffrepos.bricknetcenter.util.gui.inputcomponent;

import java.text.ParseException;
import java.util.Date;
import javax.swing.JTextField;
import net.stuffrepos.bricknetcenter.util.LocaleHelper;
import net.stuffrepos.bricknetcenter.util.gui.inputcomponent.InputComponentValueParser.ValueResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Eduardo H. Bogoni <eduardobogoni@gmail.com>
 */
public class TextFieldDateParser implements InputComponentValueParser<JTextField, Date> {

    private static final Log log = LogFactory.getLog(TextFieldDateParser.class);

    @Override
    public ValueResult<Date> fromComponent(JTextField component) {
        if (component.getText().trim().isEmpty()) {
            return new ValueResult<Date>(null, true);
        } else {
            try {
                return new ValueResult<Date>(LocaleHelper.getDateOnlyInputFormat().parse(component.getText().trim()), true);
            } catch (ParseException ex) {
                return new ValueResult<Date>(null, false);
            }
        }

    }

    @Override
    public void toComponent(JTextField component, Date value) {
        if (value == null) {
            component.setText("");
        } else {
            component.setText(LocaleHelper.getDateOnlyInputFormat().format(value));
        }

    }

    @Override
    public void setEditable(JTextField component, boolean editable) {
        component.setEditable(editable);
    }
}
